<template>
  <div class="container">
    <el-form
      :inline="true"
      :model="params"
      label-width="70px"
      label-position="left"
      size="mini"
      class="demo-form-inline"
      style="padding-top: 18px;"
      @submit.native.prevent
    >
      <el-form-item label="商户">
        <el-select v-model="params.merchantId" placeholder="请选择">
          <el-option label="请选择商户" value></el-option>
          <el-option
            v-for="item in merchantList"
            :key="item.merchantId"
            :label="item.merchantName"
            :value="Number(item.merchantId)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-date-picker
          v-model="params.yearMonth"
          type="month"
          value-format="yyyyM"
          placeholder="选择月份"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="批次ID">
        <el-input clearable v-model="params.batchId" placeholder="批次ID" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="批次名称">
        <el-input clearable v-model="params.batchName" placeholder="批次名称" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="params.status" placeholder="请选择">
          <el-option label="请选择" value></el-option>
          <el-option value="1" label="已结算"></el-option>
          <el-option value="0" label="未结算"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="doSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="button-field">
      <el-button type="primary" size="small" @click="doExport">导出</el-button>
    </div>
    <el-table
      @select-all="onSelectAll"
      @select="onRowSelect"
      :data="tableData"
      style="width: 100%"
      border
      size="small"
      stripe
      :empty-text="emptyText"
      height="300"
    >
      <el-table-column fixed type="index" width="55" align="center"></el-table-column>
      <el-table-column prop="shopName" label="使用商户" width="180"></el-table-column>
      <el-table-column prop="yearMonth" label="年月" width="180"></el-table-column>
      <el-table-column prop="batchId" label="批次ID" width="180"></el-table-column>
      <el-table-column prop="batchName" label="批次名称" width="180"></el-table-column>
      <!--20200813 许云飞反馈 发券主体以及费用归属由枚举值改为了文字-->
      <!-- <el-table-column prop="provider" label="发券主体" width="180" :formatter="providerFormat"></el-table-column>
      <el-table-column prop="providerCode" label="费用归属" width="180" :formatter="typeFormat"></el-table-column>-->
      <el-table-column prop="provider" label="发券主体" width="180"></el-table-column>
      <el-table-column prop="providerCode" label="费用归属" width="180"></el-table-column>
      <el-table-column prop="useNum" label="使用数量" width="180"></el-table-column>
      <el-table-column prop="writtenMoney" label="核销金额" width="180"></el-table-column>
      <el-table-column prop="refundNum" label="返还数量" width="180"></el-table-column>
      <el-table-column prop="refundMoney" label="返还金额" width="180"></el-table-column>
      <el-table-column prop="status" label="结算状态" width="180"></el-table-column>
      <el-table-column fixed="right" prop label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="doSettlement(scope.row)"
            v-if="scope.row.status !== '已结算'"
          >结算</el-button>
          <el-button type="text" size="small" @click="showLog(scope.row)">日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-area" style>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageSize"
        :current-page.sync="params.pageIndex"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        :page-count="pageCount"
      ></el-pagination>
    </div>
    <el-dialog title="财务结算日志" :visible.sync="dialogVisible" width="800">
      <el-table :data="logs" border size="small" stripe>
        <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
        <el-table-column width="100" prop="createBy" label="操作人"></el-table-column>
        <el-table-column width="150" prop="operateDesc" label="操作类型"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="remark" label="操作说明" width="100"></el-table-column>
      </el-table>
      <div class="pagination-area">
        <el-pagination
          background
          @size-change="handleLogSizeChange"
          @current-change="handleLogCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="logParams.pageSize"
          :current-page.sync="logParams.pageIndex"
          layout="total, sizes, prev, pager, next, jumper"
          :total="logParams.totalCount"
          :page-count="logParams.pageCount"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFinanceReportList,
  getActivityLog,
  doSettlement,
  getMerchant,
  exportExcel,
} from '@/api/coupon'
import { getStatusNameByStatus } from '@/utils/status'

export default {
  name: "couponList",
  data() {
    return {
      merchantList: [],
      // 用于显示或隐藏日志弹窗
      dialogVisible: false,
      logParams: {
        pageIndex: 1,
        pageSize: 10,
        // 总条目数
        totalCount: 100,
        // 总页数
        pageCount: 0,
        rowId: "",
      },
      params: {
        // 每页条数
        pageSize: 10,
        // 页码
        pageIndex: 1,
        // 时间
        yearMonth: "",
        // 优惠券批次id
        batchId: "",
        // 优惠券批次名称
        batchName: "",
        // 状态
        status: "",
        // 商户id
        merchantId: "",
      },
      emptyText: "",
      // 总条目数
      totalCount: 100,
      // 总页数
      pageCount: 0,
      ids: [],
      tableData: [],
      logs: [],
    };
  },
  created() {
    this.getMerchantList();
  },
  methods: {
    // 查询商家
    async getMerchantList() {
      const res = await getMerchant();
      console.log(res);
      this.merchantList = res;
    },
    // 结算
    doSettlement(row) {
      this.$confirm("确定对该商户进行财务结算？", "结算财务确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确定
          doSettlement(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.doSearch();
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error",
              });
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 导出
    async doExport() {
      const params = {
        batchId: this.params.batchId,
        batchName: this.params.batchName,
        merchantId: this.params.merchantId,
        status: this.params.status,
        yearMonth: this.params.yearMonth,
      };
      
      const blob = await exportExcel(
        this.params.pageSize,
        this.params.pageIndex,
        params
      );

      const filename = "export.xlsx";

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, filename);
      } else {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    },
    // 监听选中事件
    onRowSelect(selection, row) {
      this.ids = selection.map((item) => item.id);
    },
    // 全选
    onSelectAll(selection) {
      this.ids = selection.map((item) => item.id);
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageIndex = 1;

      this.getFinanceReportList();
    },
    handleCurrentChange(pageIndex) {
      this.params.pageIndex = pageIndex;
      this.getFinanceReportList();
    },
    handleLogSizeChange(pageSize) {
      this.logParams.pageSize = pageSize;
      this.logParams.pageIndex = 1;

      this.getLogs();
    },
    handleLogCurrentChange(pageIndex) {
      this.params.pageIndex = pageIndex;
      this.getLogs();
    },
    statusFormat(row, column, cellValue, index) {
      return getStatusNameByStatus(cellValue);
    },
    batchMoneyFormat(row, column, cellValue, index) {
      if (row.batchDiscount) {
        return row.batchDiscount * 100 + "%";
      }
      return cellValue;
    },
    batchTypeFormat(row, column, cellValue, index) {
      return cellValue === "0" ? "现金券" : "满减券";
    },
    providedTypeFormat(row, column, cellValue, index) {
      return cellValue === "0" ? "定向发放" : "非定向发放";
    },
    providerFormat(row, column, cellValue, index) {
      return cellValue === "0" ? "平台" : "商家";
    },
    typeFormat(row, column, cellValue, index) {
      return cellValue === "0" ? "便捷青岛" : "商户";
    },
    toAddConfig() {
      this.$router.push({
        path: "/addconfig",
        query: {
          viewType: "add",
        },
      });
    },
    batchReview() {
      const ids = this.ids;
      batchAuditList(ids).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.refresh();
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },
    doSearch() {
      this.params.pageIndex = 1;
      this.getFinanceReportList();
    },
    getFinanceReportList() {
      // 加载优惠券列表
      getFinanceReportList(this.params.pageIndex, this.params.pageSize, {
        batchId: this.params.batchId,
        batchName: this.params.batchName,
        status: this.params.status,
        merchantId: this.params.merchantId,
        yearMonth: this.params.yearMonth,
      }).then((res) => {
        // Todo
        // 如果成功返回 设置数据
        // 否则提示
        if (res.code === 200) {
          this.tableData = res.result.records;
          this.totalCount = res.result.total;
          this.pageCount = res.result.pages;
        } else {
          this.tableData = [];
          this.emptyText = res.msg;
          this.totalCount = 0;
          this.pageCount = 0;
        }
      });
    },
    getLogs() {
      getActivityLog({
        id: this.logParams.rowId,
        type: 2,
        pageIndex: this.logParams.pageIndex,
        pageSize: this.logParams.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.logs = res.result.records;
          this.logParams.totalCount = res.result.total;
          this.logParams.pageCount = res.result.pages;
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },
    showLog(row) {
      this.logParams.rowId = row.id;
      getActivityLog({
        id: this.logParams.rowId,
        type: 2,
        pageIndex: this.logParams.pageIndex,
        pageSize: this.logParams.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.logs = res.result.records;
          this.logParams.totalCount = res.result.total;
          this.logParams.pageCount = res.result.pages;
          this.dialogVisible = true;
          console.log(res);
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
      // this.dialogVisible = true;
    },
    toEdit(item) {
      this.$router.push({
        path: "/editconfig",
        query: {
          viewType: "edit",
          couponId: item.id,
        },
      });
    },
    toDetail(item) {
      this.$router.push({
        path: "/showconfig",
        query: {
          viewType: "detail",
          couponId: item.id,
        },
      });
    },
    refresh() {
      this.pageIndex = 1;
      this.getFinanceReportList();
    },
    doCancel(row) {
      this.$confirm("请确认是否作废当前优惠券批次？", "作废确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 确定
        cancelCoupon(row.id).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "作废成功",
              type: "success",
            });
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        });
      });
    },
    doCopy(row) {
      this.$confirm("请确认是否复制当前优惠券批次？", "复制确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        copyCoupon(row.id).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        });
      });
    },
    // 提交审核
    doExamine(row) {
      auditCoupons(rows.id).then((res) => {
        if (res.code !== 200) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },
  },
  mounted() {
    // 加载优惠券列表
    this.getFinanceReportList();
  },
};
</script>

<style lang="scss">
</style>